package com.zu.commu.local;

import com.zu.commu.context.ServerContext;
import com.zu.commu.local.threads.LocalReadThreadManager;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class LocalServer {
	Logger log = Logger.getLogger(LocalServer.class);
	private static ServerSocketChannel serverChannel;
	private static ServerSocket serverSocket;
	private static Selector selector;

	public static Selector getSelector() {
		return selector;
	}

	public void startServer() {
		try {
			serverChannel = ServerSocketChannel.open();
			serverChannel.configureBlocking(false);
			serverSocket = serverChannel.socket();
			InetSocketAddress inetAddress = new InetSocketAddress(
					ServerContext.localPort);
			serverSocket.bind(inetAddress);

			selector = Selector.open();
			serverChannel.register(selector, 16);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		System.out.println("@@ CommuServer local—PORT : "
				+ ServerContext.localPort + " @@");

		ServerContext.localServerStarted = Boolean.valueOf(true);
		while (true) {
			int numKeys = 0;
			try {
				Thread.sleep(100L);
				numKeys = selector.select();
				log.debug("localServer 收到新的连接！");
				if (numKeys > 0) {
					Set<SelectionKey> readyKeys = selector.selectedKeys();
					for (Iterator<SelectionKey> ite = readyKeys.iterator(); ite
							.hasNext();) {
						SelectionKey oneKey = ite.next();
						ite.remove();

						if (oneKey.isAcceptable()) {
							try {
								ServerSocketChannel server = (ServerSocketChannel) oneKey
										.channel();
								SocketChannel channel = server.accept();
								channel.configureBlocking(false);
								channel.register(selector, 1);
							} catch (IOException e2) {
								e2.printStackTrace();
							}

						} else {
							// if ((!oneKey.isReadable())||(oneKey.attachment()
							// != null)) {
							if (!oneKey.isReadable()) {
								continue;
							}
							oneKey.attach(new Object());
							SocketChannel local = (SocketChannel) oneKey
									.channel();

							LocalReadThreadManager.instance().readSocketChannel(local);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();

			}
		}
	}
}